import tkinter as tk
from tkinter import ttk, Text
from tkinter import messagebox
#import webbrowser
#import os
#import re
import pandas as pd
from openpyxl import load_workbook
#from datetime import datetime
#from tkcalendar import DateEntry
from rental import Rental
from tenant import Tenant
from setting import Setting
from receipt import Receipt

class Datepicker:
    def __init__(self, parent):
        self.setting = Setting()
        self.url_fileRoomInfo = self.setting.url_fileRoomInfo
        self.url_filePrice = self.setting.url_filePrice
        self.parent = parent
        self.start()

    def start(self): #启动，创建两个页签
        notebook = ttk.Notebook(root)
        notebook.pack(expand=True, fill="both")
        # > 标签1
        self.frame1 = ttk.Frame(root)
        # > 标签2
        frame2 = ttk.Frame(root, height=500)
        # > 标签3
        frame3 = ttk.Frame(root)
        # > 标签4
        frame4 = ttk.Frame(root)

        notebook.add(self.frame1, text="首页")
        notebook.add(frame2, text="租客管理")
        notebook.add(frame3, text="收租管理")
        notebook.add(frame4, text="收据生成")
        """#首页管理"""
        self.Homepage() #首页
        #self.tenantManger(frame2)
        """#房间管理"""
        tenant = Tenant()
        tenant.tenantManger(frame2)
        """#收租管理"""
        rental = Rental()
        rental.rentalManger(frame3)
        """#收据管理"""
        receipt = Receipt()
        receipt.receiptManger(frame4)
    def frame1PriceShow(self):
        df = pd.read_excel(self.url_filePrice, 'Price', engine='openpyxl', header=0)
        warterPrice = df.iloc[0, 0]
        electricPrice = df.iloc[0, 1]
        self.LTwarter.config(text = '水费单价(元/吨)：' + str(warterPrice))
        self.LTelectric.config(text = '电费单价(元/度)：' + str(electricPrice))
        self.setting.reloadENT(self.enTwarterprice, warterPrice)
        self.setting.reloadENT(self.enTelectricprice, electricPrice)
        #设置水电价格变更，方便其它方法调用
        self.setting.set_warterPrice(warterPrice)
        self.setting.set_electricPrice(electricPrice)

    def frame1HomepageShow(self): #在首页展示房间号，可重复调用，调用后会进行覆盖
        s_la = self.setting.roomList(self.url_fileRoomInfo, 'RoomInfo')
        num = 0
        rowNum = 1  # 行号控制
        colNum = 0
        for i in s_la:
            label = ttk.Label(self.canvas1, text=i, background="white", relief="solid", padding=(5, 5), width=8,
                              font=("微软雅黑", 10), anchor="center")
            label.grid(row = rowNum, column = colNum)
            num = num + 1
            rowNum = (num // 5) + 1
            colNum = num % 5
        #补充一个空行，方便删除后的显示
        label = ttk.Label(self.canvas1, text='', background="white", relief="solid", padding=(5, 5), width=8,
                          font=("微软雅黑", 10), anchor="center")
        label.grid(row=rowNum, column=colNum)

    #添加内容
    def insert_row_to_excel(self, file_path, row_data, sheet_name, row_index):
        df = pd.read_excel(file_path, sheet_name=sheet_name, engine='openpyxl', header=None)
        df.loc[row_index+1, 0] = row_data
        # 将DataFrame对象写入特定的工作表和行
        df.to_excel(file_path, index=False, header=False, sheet_name=sheet_name, startrow=0)

    def Homepage(self): # 首页
        """设置布局"""
        self.canvas2 = tk.Canvas(self.frame1, width=300, height=50)
        self.canvas2.pack(side=tk.TOP)
        self.canvas3 = tk.Canvas(self.frame1, width=300, height=50)
        self.canvas3.pack(side=tk.TOP)
        self.canvas4 = tk.Canvas(self.frame1, width=500, height=50)
        self.canvas4.pack(side=tk.TOP)
        self.canvas1 = tk.Canvas(self.frame1, width=500, height=300)
        self.canvas1.pack(side=tk.TOP)

        LabelTitler = ttk.Label(self.canvas4, text="房间号", relief="solid", width=10,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=0)
        self.enT = ttk.Entry(self.canvas4)
        self.enT.grid(row=0, column=1)
        hpBtn1 = ttk.Button(self.canvas4, text="添加", command=self.addHome)
        hpBtn1.grid(row=0, column=2)
        hpBtn2 = ttk.Button(self.canvas4, text="删除", command=self.delHome)
        hpBtn2.grid(row=0, column=3)
        self.frame1HomepageShow()

        self.LTwarter = ttk.Label(self.canvas2, text="水费单价(元/吨)：", relief="solid", width=16,
                                font=("微软雅黑", 10, "bold"), anchor="w")
        self.LTwarter.grid(row=0, column=0)
        self.enTwarterprice = ttk.Entry(self.canvas2, width=8, justify="center")
        self.enTwarterprice.grid(row=0, column=1)
        self.LTelectric = ttk.Label(self.canvas2, text="电费单价(元/度)：", relief="solid", width=16,
                                font=("微软雅黑", 10, "bold"), anchor="w")
        self.LTelectric.grid(row=1, column=0)
        self.enTelectricprice = ttk.Entry(self.canvas2, width=8, justify="center")
        self.enTelectricprice.grid(row=1, column=1)
        hpBtn4 = ttk.Button(self.canvas2, text="调整", command=self.adjustPrice)
        hpBtn4.grid(row=2, column=0, columnspan=2)
        self.frame1PriceShow()


    def addHome(self): #添加房间
        rowNUM = self.enT.get()
        lineText = self.setting.roomList(self.url_fileRoomInfo, 'RoomInfo')
        if rowNUM in lineText:
            messagebox.showwarning("告警", "房间已存在！")
        else:
            row_data = rowNUM  # 要插入的行数据
            sheet_name = 'RoomInfo'  # 要插入数据的工作表名称
            row_index = len(lineText)  # 要插入数据的行索引（从0开始）
            self.insert_row_to_excel(self.url_fileRoomInfo, row_data, sheet_name, row_index)
            self.frame1HomepageShow() #重新展示房间

    def delHome(self): #删除房间
        rowNUM = self.enT.get()
        s_la = self.setting.roomList(self.url_fileRoomInfo, 'RoomInfo')
        if rowNUM in s_la:
            row_data = rowNUM  # 要插入的行数据
            sheet_name = 'RoomInfo'  # 要插入数据的工作表名称
            self.setting.del_row_to_excel(self.url_fileRoomInfo, row_data, sheet_name)
            self.frame1HomepageShow() #重新展示房间
        else:
            messagebox.showwarning("告警", "房间不存在！")

    def adjustPrice(self):
        df = pd.read_excel(self.url_filePrice, sheet_name='Price', engine='openpyxl', header=None)
        df.loc[1, 0] = self.enTwarterprice.get()
        df.loc[1, 1] = self.enTelectricprice.get()
        # 将DataFrame对象写入特定的工作表和行
        df.to_excel(self.url_filePrice, index=False, header=False, sheet_name='Price', startrow=0)
        self.frame1PriceShow()
        messagebox.showwarning("提示", "调整成功！")


if __name__ == '__main__':
    root = tk.Tk()
    root.title("收租系统")
    root.geometry("1080x700")
    Datepicker(root)
    root.mainloop()


